package com.cpic.blood.admin.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.cpic.blood.core.config.OSSConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
public class FileUploadService {

    @Autowired
    private OSSConfig ossConfig;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    public String uploadFile(MultipartFile file) throws IOException {
        // 生成唯一文件名
        String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();

        OSS ossClient = ossConfig.ossClient();

        // 设置文件上传的元信息
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(file.getSize());
        metadata.setContentType(file.getContentType());

        // 上传文件到OSS
        ossClient.putObject(bucketName, fileName, file.getInputStream(), metadata);

        // 返回文件在OSS中的访问URL
        return "https://" + bucketName + "." + ossConfig.getEndpoint() + "/" + fileName;
    }
}
